//
//  CustomAnnotationView.m
//  CustomAnnotationDemo
//
//  Created by songjian on 13-3-11.
//  Copyright (c) 2013年 songjian. All rights reserved.
//

#import "CustomAnnotationView.h"
#import "XDXPointAnnotation.h"

@interface CustomAnnotationView ()

// 记录上一次 cor 的状态，用于避免“原地转圈”重复动画
@property (nonatomic, assign) CGPoint xdx_lastPoint;
@property (nonatomic, assign) CGFloat xdx_lastAngle;
@property (nonatomic, assign) CGFloat xdx_lastDistance;
@property (nonatomic, assign) BOOL    xdx_hasLastState;

@end

@implementation CustomAnnotationView



#pragma mark - Handle Action

// 为 cor 动画做的容差，用于判断“是否真的有变化”
static const CGFloat kXDXPosEps   = 0.5f;   // 位置小于 0.5pt 认为没变
static const CGFloat kXDXAngleEps = 0.01f;  // 角度小于约 0.57° 认为没变
static const CGFloat kXDXDistEps  = 0.5f;   // 距离小于 0.5pt 认为没变

// 复用前重置可变状态，防止上一实例的旋转/锚点/尺寸污染
- (void)prepareForReuse
{
    [super prepareForReuse];

    self.xdx_hasLastState = NO;
}

- (void)btnAction
{
    CLLocationCoordinate2D coorinate = [self.annotation coordinate];
    
    NSLog(@"coordinate = {%f, %f}", coorinate.latitude, coorinate.longitude);
}

- (void)xdx_updateCorWithAngle:(CGFloat)angle Point:(CGPoint)point distance:(CGFloat)distance
{
    if (self.view.hidden) {
        return;
    }

    // ===== 1. 如果 point / angle / distance 基本没变，则不再做重复动画，避免“原地转圈”的感觉 =====
    BOOL samePoint = (fabs(point.x - self.xdx_lastPoint.x) < kXDXPosEps &&
                      fabs(point.y - self.xdx_lastPoint.y) < kXDXPosEps);
    BOOL sameAngle = (fabs(angle - self.xdx_lastAngle) < kXDXAngleEps);
    BOOL sameDist  = (fabs(distance - self.xdx_lastDistance) < kXDXDistEps);

    if (self.xdx_hasLastState && samePoint && sameAngle && sameDist) {
        // 上一帧和这一帧几乎一模一样，直接退出，不再触发 0.3s 动画
        return;
    }

    // 记录这一次的状态
    self.xdx_hasLastState  = YES;
    self.xdx_lastPoint     = point;
    self.xdx_lastAngle     = angle;
    self.xdx_lastDistance  = distance;
    
    // 目标：以圆心为锚点，从圆心到远端的长度 = distance
    CGFloat newHeight = distance+kPortraitWidth/2;
    if (newHeight<(kPortraitWidth+7)) {
        newHeight = (kPortraitWidth+7);
        
        UIImage *img = [UIImage imageNamed:@"location_cor"];
        self.viewLayer.contents      = (__bridge id)img.CGImage;
        // 以“点”为单位定义不拉伸的四边
        CGFloat topCap    = kPortraitWidth;   // 上面 64pt 不拉伸
        CGFloat bottomCap = 0;
        CGFloat leftCap   = 0;
        CGFloat rightCap  = 0;

        // 用图片真实 size 来归一化
        CGFloat w = img.size.width;
        CGFloat h = img.size.height;
        _viewLayer.contentsCenter = CGRectMake(leftCap / w,
                                               topCap  / h,
                                               (w - leftCap - rightCap) / w,
                                               (h - topCap - bottomCap) / h);
        [UIView animateWithDuration:0.3 animations:^{
            self.transform = CGAffineTransformMakeTranslation(0, 0);
            self.view.layer.transform = CATransform3DIdentity;
            self.portraitImageView.layer.transform = CATransform3DIdentity;
            self.view.transform = CGAffineTransformIdentity;
        }];
    }else{
        UIImage *img = [UIImage imageNamed:@"avatar_large"];
        self.viewLayer.contents      = (__bridge id)img.CGImage;
        // 以“点”为单位定义不拉伸的四边
        CGFloat topCap    = kPortraitWidth;   // 上面 64pt 不拉伸
        CGFloat bottomCap = 0;
        CGFloat leftCap   = 0;
        CGFloat rightCap  = 0;

        // 用图片真实 size 来归一化
        CGFloat w = img.size.width;
        CGFloat h = img.size.height;
        _viewLayer.contentsCenter = CGRectMake(leftCap / w,
                                               topCap  / h,
                                               (w - leftCap - rightCap) / w,
                                               (h - topCap - bottomCap) / h);
    }
    CGRect bounds = self.viewLayer.bounds;
    bounds.size.height = newHeight;
    self.viewLayer.bounds = bounds;
    self.viewLayer.frame = CGRectMake(0, 0, bounds.size.width, newHeight);
    CGFloat baseOffset = -M_PI_2;

    self.view.layer.anchorPoint = CGPointMake(0.5, (kPortraitHeight/2)/(kPortraitHeight+7));
    [UIView animateWithDuration:0.3 animations:^{
        // 1. 先计算缩放比例
        CGFloat scale = 0.8f;   // 你现在用的 0.8

        // 2. 根据缩放“少出来的半径”再沿着 point 方向多走一点距离
        CGFloat radius = kPortraitWidth * 0.5f;          // 头像半径
        CGFloat len    = hypot(point.x, point.y);
        CGFloat extraX = 0.f;
        CGFloat extraY = 0.f;
        if (len > 1e-3f) {
            // 这一段 delta 可以理解为：缩小后少出来的那一圈，用它来继续拉远一点
            CGFloat delta = (1.0f - scale) * radius;
            extraX = point.x / len * delta;
            extraY = point.y / len * delta;
        }

        // 原来的 point 再加上额外的“拉远量”，让缩小后的 self.view 继续贴近原点
        self.transform = CGAffineTransformMakeTranslation(point.x - extraX,
                                                          point.y - extraY);

        // 3. 再做旋转 + 缩放
        CATransform3D rotate = CATransform3DMakeRotation(angle + baseOffset, 0, 0, 1);
        self.view.layer.transform = CATransform3DScale(rotate, scale, scale, 1.0);
        self.portraitImageView.layer.transform = CATransform3DScale(CATransform3DMakeRotation(0, 0, 0, 1), scale, scale, 1.0);
    }];
    self.portraitImageView.center = self.view.center;
}

- (void)xdx_resetCorToDefault
{    
    self.viewLayer.frame      = self.view.bounds;      // 恢复到 init 时的大小
    UIImage *img = [UIImage imageNamed:@"location_cor"];
    self.viewLayer.contents      = (__bridge id)img.CGImage;
    // 以“点”为单位定义不拉伸的四边
    CGFloat topCap    = kPortraitWidth;   // 上面 64pt 不拉伸
    CGFloat bottomCap = 0;
    CGFloat leftCap   = 0;
    CGFloat rightCap  = 0;

    // 用图片真实 size 来归一化
    CGFloat w = img.size.width;
    CGFloat h = img.size.height;
    _viewLayer.contentsCenter = CGRectMake(leftCap / w,
                                           topCap  / h,
                                           (w - leftCap - rightCap) / w,
                                           (h - topCap - bottomCap) / h);
    [UIView animateWithDuration:0.3 animations:^{
        self.transform = CGAffineTransformMakeTranslation(0, 0);
        self.view.layer.transform = CATransform3DIdentity;
        self.portraitImageView.layer.transform = CATransform3DIdentity;
        self.view.transform = CGAffineTransformIdentity;
    }];
}

#pragma mark - Life Cycle

- (instancetype)initWithAnnotation:(nullable id <MKAnnotation>)annotation reuseIdentifier:(nullable NSString *)reuseIdentifier
{
    self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
    
    if (self)
    {
        // 初始化重叠管理属性
        self.centerOffset = CGPointMake(0, -kWidth/2-7);
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [[tap rac_gestureSignal] subscribeNext:^(id x) {
            if ([self.annotation isKindOfClass:[XDXPointAnnotation class]]) {
                if (((XDXPointAnnotation *)self.annotation).anns.count==0) {
                    self.CustomAnnotationClickBlock();
                }
            }else{
                self.CustomAnnotationClickBlock();
            }
        }];
        [self addGestureRecognizer:tap];
        
        self.bounds = CGRectMake(0.f, 0.f, kWidth, kHeight);
        self.view = [[UIImageView alloc] initWithFrame:CGRectMake((kWidth-kPortraitWidth)/2, kPortraitHeight, 0, 0)];
        [self addSubview:self.view];
        
        _viewLayer = [CALayer layer];
        _viewLayer.frame = self.view.bounds;
        _viewLayer.cornerRadius = 28;
        _viewLayer.masksToBounds = NO;
        _viewLayer.shadowColor = RealBlackColor.CGColor;
        _viewLayer.shadowOffset = CGSizeMake(0,2);
        UIImage *img = [UIImage imageNamed:@"location_cor"];
        _viewLayer.contents      = (__bridge id)img.CGImage;
        _viewLayer.contentsScale = img.scale;
        _viewLayer.contentsGravity = kCAGravityResize;

        // 以“点”为单位定义不拉伸的四边
        CGFloat topCap    = kPortraitWidth;
        CGFloat bottomCap = 0;
        CGFloat leftCap   = 0;
        CGFloat rightCap  = 0;

        // 用图片真实 size 来归一化
        CGFloat w = img.size.width;
        CGFloat h = img.size.height;
        _viewLayer.contentsCenter = CGRectMake(leftCap / w,
                                               topCap  / h,
                                               (w - leftCap - rightCap) / w,
                                               (h - topCap - bottomCap) / h);
        _viewLayer.shadowOpacity = 0.3;
        _viewLayer.shadowRadius = 3;
        [self.view.layer addSublayer:_viewLayer];
        
        _groupView = [[UIView alloc] initWithFrame:CGRectMake((kWidth-kGroupWidth)/2, kHeight-kPortraitHeight, kGroupWidth, kPortraitHeight)];
        [self addSubview:_groupView];                
                        
        _portraitImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kWidth/2, kPortraitHeight, 0, 0)];
        _portraitImageView.userInteractionEnabled = YES;
        _portraitImageView.contentMode = UIViewContentModeScaleAspectFill;
        _portraitImageView.layer.cornerRadius = 0;
        [_portraitImageView.layer setBorderColor:RealWhiteColor.CGColor];
        [_portraitImageView.layer setBorderWidth:kHoriMargin];
        _portraitImageView.layer.masksToBounds = YES;
        [self addSubview:_portraitImageView];
                    
//        self.countLabel = [[UILabel alloc] initWithFrame:CGRectMake((kWidth-(kPortraitWidth+2*kHoriMargin))/2+kPortraitWidth+2*kHoriMargin-15, self.bounds.size.height/2-20, 20, 20)];
//        self.countLabel.layer.masksToBounds = YES;
//        [self.countLabel.layer setCornerRadius:10];
//        self.countLabel.textAlignment = NSTextAlignmentCenter;
//        self.countLabel.backgroundColor = RealBlackColor;
//        self.countLabel.textColor = RealWhiteColor;
//        self.countLabel.hidden = YES;
//        self.countLabel.font = MEDIUM_FONT(12);
//        [self addSubview:self.countLabel];
        
        self.locationCircle = [[UIView alloc] initWithFrame:CGRectMake((self.bounds.size.width-20)/2, self.bounds.size.height-3, 20, 20)];
        self.locationCircle.layer.masksToBounds = YES;
        [self.locationCircle.layer setCornerRadius:10];
        [self.locationCircle.layer setBorderWidth:1];
        [self.locationCircle.layer setBorderColor:NormalMainColor.CGColor];
        self.locationCircle.backgroundColor = [ThitMainColor colorWithAlphaComponent:0.2];
        [self insertSubview:self.locationCircle atIndex:0];

        self.heading = [[UIImageView alloc] initWithFrame:CGRectMake((kWidth-260)/2, 0, 260, 260)];
        self.heading.userInteractionEnabled = YES;
        self.heading.centerY = self.view.maxY+7;
        [self insertSubview:self.heading atIndex:1];
        
        UIImageView *head = [[UIImageView alloc] initWithFrame:CGRectMake((self.heading.width-76)/2, -4 , 76, 142)];
        head.image = [UIImage imageNamed:@"jianbianjiantou"];
        head.userInteractionEnabled = YES;
        [self.heading addSubview:head];
        
        UIView *headDot = [[UIImageView alloc] initWithFrame:CGRectMake((head.width-10)/2, head.height-13, 10, 10)];
        headDot.backgroundColor = NormalMainColor;
        headDot.layer.masksToBounds = YES;
        [headDot.layer setCornerRadius:5];
        [head addSubview:headDot];
        
        self.selView = [[UIView alloc] initWithFrame:CGRectMake((kWidth-(kPortraitWidth+64))/2, (kHeight-(kPortraitHeight+64))/2, kPortraitWidth+64, kPortraitHeight+64)];
        self.selView.hidden = YES;
        [self addSubview:self.selView];
        
        self.borderColor = DeepMainCoolor;
        self.circle = [[UIView alloc] initWithFrame:CGRectMake(32-kHoriMargin, 32-kVertMargin, kPortraitWidth+2*kHoriMargin, kPortraitWidth+2*kVertMargin)];
        [self.circle.layer setBorderWidth:0];
        [self.circle.layer setBorderColor:[self.borderColor colorWithAlphaComponent:0.5].CGColor];
        [self.circle.layer setCornerRadius:self.circle.width*0.44];
        [self.selView addSubview:self.circle];
        
        UIView *battey = [[UIView alloc] initWithFrame:CGRectMake((self.selView.width-63)/2, self.selView.height-20, 63, 20)];
        battey.backgroundColor = RealBlackColor;
        battey.layer.masksToBounds = YES;
        [battey.layer setCornerRadius:10];
        [self.selView addSubview:battey];
        
        _batteyImg = [[UIImageView alloc] initWithFrame:CGRectMake(10, (battey.height-20)/2, 20, 20)];
        _batteyImg.image = [UIImage imageNamed:@"battery"];
        _batteyImg.contentMode = UIViewContentModeScaleAspectFit;
        [battey addSubview:_batteyImg];
        
        _batteyView = [[UILabel alloc] initWithFrame:CGRectMake(_batteyImg.x+3, _batteyImg.y+8, 13, 5)];
        _batteyView.backgroundColor = RealWhiteColor;
        _batteyView.layer.masksToBounds = YES;
        [_batteyView.layer setCornerRadius:1];
        [battey insertSubview:_batteyView belowSubview:_batteyImg];
        
        _battey = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_batteyImg.frame)+4, 0, 22, battey.height)];
        _battey.font = MEDIUM_FONT(10);
        _battey.textColor = RealWhiteColor;
        [battey addSubview:_battey];
        
//        _activitySmallView = [[UIView alloc] initWithFrame:CGRectMake(kWidth-18, -11, 30, 26)];
//        _activitySmallView.alpha = 0;
//        [self addSubview:_activitySmallView];
//        
//
//        
//        _activitySmallImg = [[UIImageView alloc] initWithFrame:CGRectMake((_activitySmallView.width-18)/2, (_activitySmallView.height-18)/2, 18, 18)];
//        [_activitySmallView addSubview:_activitySmallImg];
        
        _activityView = [[UIView alloc] initWithFrame:CGRectMake(_selView.maxX-54, self.selView.y+21, 30, 26)];
//        _activityView.alpha = 0;
        [self addSubview:_activityView];
       
        
        _activityLayer = [CALayer layer];
        _activityLayer.frame = self.activityView.bounds;
        _activityLayer.cornerRadius = _activityView.height/2;
        _activityLayer.masksToBounds = NO;
        _activityLayer.backgroundColor = RealWhiteColor.CGColor;
        _activityLayer.shadowColor = RealBlackColor.CGColor;
        _activityLayer.shadowOffset = CGSizeMake(0,2);
        _activityLayer.shadowOpacity = 0.3;
        _activityLayer.shadowRadius = 3;
        [self.activityView.layer addSublayer:_activityLayer];
        
        _activityImg = [[UIImageView alloc] initWithFrame:CGRectMake(6, (_activityView.height-18)/2, 18, 18)];
        _activityImg.layer.masksToBounds = YES;
        [_activityView addSubview:_activityImg];
        
        _activity = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_activityImg.frame)+3, 0, 57, _activityView.height)];
//        _activity.alpha = 0;
        _activity.layer.masksToBounds = YES;
        _activity.font = MEDIUM_FONT(13);
        _activity.textColor = RealBlackColor;
        [_activityView addSubview:_activity];
        
        _activityView.transform = CGAffineTransformMakeScale(1.0/30, 1.0/35);
        
        [self animation];
    }
    
    return self;
}

- (void)animation
{
    [UIView animateWithDuration:3.0 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        [self.circle setFrame:CGRectMake(0, 0, kPortraitWidth+64, kPortraitHeight+64)];
        [self.circle.layer setBorderColor:[self.borderColor colorWithAlphaComponent:0.0].CGColor];
        [self.circle.layer setBorderWidth:32];
        [self.circle.layer setCornerRadius:self.circle.width*0.44];
    } completion:^(BOOL finished) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.circle setFrame:CGRectMake(32-kHoriMargin, 32-kVertMargin, kPortraitWidth+2*kHoriMargin, kPortraitWidth+2*kVertMargin)];
            [self.circle.layer setBorderColor:[self.borderColor colorWithAlphaComponent:0.5].CGColor];
            [self.circle.layer setBorderWidth:0];
            [self.circle.layer setCornerRadius:self.circle.width*0.44];
            [self animation];
        });
    }];
}

@end
